package com.itqf.controller;


import com.itqf.annotation.RequiresPermissionsDesc;
import com.itqf.bean.DtsAdmin;
import com.itqf.bean.DtsRole;
import com.itqf.dto.DtsPermissionDto;
import com.itqf.dto.DtsSearchDto;
import com.itqf.service.DtsRoleService;
import com.itqf.util.ResponseUtil;
import com.itqf.utils.AdminResponseCode;
import com.itqf.utils.AdminResponseUtil;
import com.itqf.utils.Permission;
import com.itqf.utils.PermissionUtil;
import com.itqf.vo.PermVo;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * projectName: shop_manage
 *
 * @author: MaTianWei
 * time: 2021/7/13 19:37
 * description:角色管理模块
 */
@RestController
@CrossOrigin("*")
@RequestMapping("/admin/role/")
public class AdminRoleController {
    @Autowired
    private DtsRoleService dtsRoleService;
    //日志
    public static final Logger logger = LoggerFactory.getLogger(AdminRoleController.class);

    @RequiresAuthentication
    @GetMapping("options")
    public Object options() {
        logger.info("[角色列表] 接口开始调用!");
        List<Map> roleList = dtsRoleService.findRoleName();
        logger.debug("[角色列表]查询数据为:{}", roleList);
        logger.info("[角色列表]接口调用结束!");
        return ResponseUtil.ok(roleList);
    }


    //角色管理/admin/role/list
    @RequiresPermissions("admin:admin:list")
    @RequiresPermissionsDesc(menu = {"角色管理", "管理员"}, button = "角色查看")
    @GetMapping("list")
    public Object list(DtsSearchDto roles) {
        logger.debug("[角色列表]角色列表查询参数是", roles);
        Map role = dtsRoleService.findRoleByPage(roles);
        logger.debug("[角色列表]分页查询数据为", role);
        return ResponseUtil.ok(role);
    }


    //角色添加admin/role/create
    @RequiresPermissions("admin:role:create")
    @RequiresPermissionsDesc(menu = {"系统管理", "角色"}, button = "角色添加")
    @PostMapping("create")
    public Object create(@RequestBody DtsRole roles) {
        //1·用户名是否在数据库存在的判断
        String rolename = roles.getName();
        if (rolename == null || rolename == "") {
            logger.warn("[保存角色]接收到的用户名为null,无法注册!");
            return ResponseUtil.fail();
        }
        boolean hasUserName = dtsRoleService.checkUserName(rolename);
        if (hasUserName) {
            logger.error("[保存管理员]用户名:{},已经被注册:{}", rolename);
            return AdminResponseUtil.fail(AdminResponseCode.ADMIN_NAME_EXIST);
        }
        //2·保存用户
        roles = dtsRoleService.saveRoles(roles);
        //3·返回结果
        logger.info("[保存角色]接口调用结束,获得回显的数据为:{}", roles);
        return ResponseUtil.ok(roles);
    }




    //角色更新admin/role/update
    @RequiresPermissions("admin:role:update")
    @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "角色更新")
    @PostMapping("update")
    public Object update(@RequestBody DtsRole roles) {
        //1·完善数据
//        roles.getDesc();
        //2·修改数据
        int rows = dtsRoleService.updateRoles(roles);
        //3·返回结果
        if (rows == 0) {
            return ResponseUtil.fail();
        }
        return ResponseUtil.ok(roles);
    }






        //角色删除/admin/role/delete
        @RequiresPermissions("admin:role:delete")
        @RequiresPermissionsDesc(menu = {"系统管理", "角色"}, button = "角色删除")
        @PostMapping("delete")
       public Object delete(@RequestBody DtsRole roles){
            logger.debug("[删除管理员]传入的id为:{}",roles.getId());
            int rows = dtsRoleService.removeRoleById(roles.getId());
            if(rows == 0){
                return ResponseUtil.fail();
            }
            logger.info("[删除角色]删除影响行数为",rows);
            return ResponseUtil.ok();
        }






        //角色授权/admin/role/permissions
        @Autowired
        public ApplicationContext applicationContext;
        @RequiresPermissions("admin:role:permissions")
        @RequiresPermissionsDesc(menu = {"系统管理", "角色管理"}, button = "权限管理")
        @GetMapping("permissions")
        public Object permissions(int roleId) {
            logger.info("[权限读取接口]开始调用查询权限的角色id为:{}", roleId);
            if (roleId == 0) {
                logger.warn("[权限读取接口]没有角色传递的id,无法查询该角色拥有的权限");
                return ResponseUtil.fail();
            }
            //1·查询程序拥有的全部权限
            List<Permission> permissionslist = PermissionUtil.listPermission(applicationContext,"com.itqf.controller");
            //2·处理结果集
            List<PermVo> permVos = PermissionUtil.listPermVo(permissionslist);
            //3·查询用户拥有的全部权限
            //判断是否是超级管理员
            boolean isSuper = dtsRoleService.checkSuper(roleId);
            Set<String> assignedPermissions = new HashSet<>();
            if (isSuper) {
                for (Permission permission : permissionslist) {
                    assignedPermissions.add(permission.getRequiresPermissions().value()[0]);
                }
            }else {
                    assignedPermissions = dtsRoleService.queryPerission(roleId);
            }
            //4·结果集封装
            Map data = new HashMap();
            data.put("systemPermissions",permVos);
            data.put("assignedPermissions",assignedPermissions);
            logger.info("[权限读取],数据读取成功,最终数据为:{}",data);
            return ResponseUtil.ok(data);
        }





        //角色权限修改
        @RequiresPermissions("admin:role:update")
        @RequiresPermissionsDesc(menu = {"系统管理","角色管理"}, button="权限修改")
        @PostMapping("permissions")
        public Object update(@RequestBody DtsPermissionDto permissionDto){
            //参数校验
            if (permissionDto.getRoleId() == 0){
                logger.error("[权限修改]传入的roleId为0,出现异常");
                return ResponseUtil.badArgument();
            }
            //清空所有[超级管理员的权限不可以改变]
            boolean isSuper = dtsRoleService.checkSuper(permissionDto.getRoleId());
            if (isSuper) {
                logger.warn("[权限修改]要修改的角色id为:{},是超级管理员,无法修改!",permissionDto.getRoleId());
                return AdminResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION);
            }
            dtsRoleService.removePermission(permissionDto.getRoleId());
            //添加新的权限
            dtsRoleService.save(permissionDto);
            return ResponseUtil.ok(null);
        }
    }




